//
//  YDPaymentPasswordController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/13.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDPaymentPasswordController.h"
#import "YDNoPastedTextField.h"
#import "OttoKeyboardView.h"

@interface YDPaymentPasswordController ()<UITextFieldDelegate,TextFieldClickReturnDelegate>

//支付密码下划线
@property (nonatomic , weak) UIView *payLineView;
//确认密码下划线
@property (nonatomic , weak) UIView *sureLineView;
//支付密码label
@property (nonatomic , weak) UILabel *payLabel;
//确认密码label
@property (nonatomic , weak) UILabel *sureLabel;

//密码输入框
@property (nonatomic , weak) OttoTextField *payPassTextField;
//确认密码框
@property (nonatomic , weak) OttoTextField *surePassTextField;
//提示label
@property (nonatomic , weak) UILabel *postLabel;

//确认按钮
@property (nonatomic , weak) SYNoHeightedButton *sureButton;

//////
@property (nonatomic , copy) NSString *payPassString;
@property (nonatomic , copy) NSString *surePayPassString;


@end

@implementation YDPaymentPasswordController


-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"支付密码";
    
    
    [self dismissKeyBoard];
    
    [self addChildViews];
    
    [self.payPassTextField addTarget:self action:@selector(textchange) forControlEvents:UIControlEventAllEditingEvents];
    [self.surePassTextField addTarget:self action:@selector(textchange) forControlEvents:UIControlEventAllEditingEvents];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_payPassTextField becomeFirstResponder];
}


-(void)textchange
{
    self.sureButton.enabled = self.payPassTextField.text.length && self.surePassTextField.text.length;
}

-(void)addChildViews
{
    //下划线
    [self payLineView];
    [self sureLineView];
    
    [self payLabel];
    [self sureLabel];
    [self payPassTextField];
    [self surePassTextField];
    [self postLabel];
    
    [self sureButton];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSArray *subviews = [self.view subviews];
    for (UITextField *textField in subviews) {
        if (textField == self.payPassTextField) {
            [self.payPassTextField resignFirstResponder];
        } else if (textField == self.surePassTextField) {
            [self.surePassTextField resignFirstResponder];
        }
    }
}

#pragma mark - TextFieldClickReturnDelegate
- (void)textFieldClickReturn:(OttoTextField *)textField
{
    [textField resignFirstResponder];
   
}

-(void)sureButtonClick:(SYNoHeightedButton *)button
{
    [self.view endEditing:YES];
    self.payPassString = self.payPassTextField.text;
    self.surePayPassString = self.surePassTextField.text;
    
    
    //判断是不是输入的纯数字
    if (![NSString isAllNum:self.payPassString] || ![NSString isAllNum:self.surePayPassString]) {

        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"密码由6位数字组成" isExistNav:YES];
    }else if (self.payPassString.length !=6 || self.surePayPassString.length != 6){

        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"密码由6位数字组成" isExistNav:YES];
    }else if (![self.payPassString isEqualToString:self.surePayPassString]){

        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"两次输入密码不相同" isExistNav:YES];
    }else{
    
        
        
        if (self.phone.length) {
            //传过来手机号 是修改支付密码
            [self sendPayPassWord:self.payPassString];
        }else
        {
            //没有手机号 为第一次设置支付密码
            [self initPayPassWord:self.payPassString];
        }
    }
}


//*****第一次上传支付密码********/////
-(void)initPayPassWord:(NSString *)passWord
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:passWord forKey:@"paymentPassword"];

    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:InitPaymentPassword WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];

        if ([resultDict[@"code"] integerValue] == 200) {
            
            //支付密码本地不存储
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeSuccess text:@"密码设置成功" isExistNav:YES];
        
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self.navigationController popViewControllerAnimated:YES];

            });
            


            
        }else{

            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"密码设置出错，请稍后重试" isExistNav:YES];
    }];
    


}

-(void)sendPayPassWord:(NSString *)passWord
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:kLoadingText];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:passWord forKey:@"paymentPassword"];
    [dict setObject:self.code forKey:@"verificationCode"];
    [dict setObject:self.phone forKey:@"phone"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:SettingPaymentPassWord WithSuccessBlock:^(NSDictionary *resultDict) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];

        if ([resultDict[@"code"] integerValue] == 200) {
            
            //支付密码本地不存储
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeSuccess text:@"密码设置成功" isExistNav:YES];
            
            
            
            UIViewController *vc = nil;
            
            NSArray *vcArr = self.drj_navigationController.drj_viewControllers;
            
            
            for (int i = 0; i < vcArr.count; i++) {
                
                vc = vcArr[i];
                
                if ([NSStringFromClass([vc class]) isEqualToString:@"YDPaymentPasswordController"])
                {
                    //跳转设置密码的上2个界面
                    vc = vcArr[i - 2];
                }
                
            }
            
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popToViewController:vc animated:YES];
                
            });
            
            
            
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"密码设置出错，请稍后重试" isExistNav:YES];
    }];
    
    
    
}

-(UIView *)payLineView
{
    if (_payLineView == nil) {
        UIView *payLineView = [[UIView alloc] init];
        [self.view addSubview:payLineView];
        //236 231 231
        payLineView.backgroundColor = NumberColor(236, 231, 231);
        [payLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(rate375(325)));
            make.centerX.equalTo(self.view);
            make.height.equalTo(@1);
            if (isPhoneX) {
                make.top.equalTo(self.view).offset(rateX812(60));
            }else{
                make.top.equalTo(self.view).offset(rate750(50));
            }
        }];
        
        _payLineView = payLineView;
    }
    return _payLineView;
}
-(UIView *)sureLineView
{
    if (_sureLineView == nil) {
        UIView *sureLineView = [[UIView alloc] init];
        [self.view addSubview:sureLineView];
        //236 231 231
        sureLineView.backgroundColor = NumberColor(236, 231, 231);
        [sureLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(rate375(325)));
            make.centerX.equalTo(self.view);
            make.height.equalTo(@1);
            if (isPhoneX) {
                make.top.equalTo(self.payLineView.mas_bottom).offset(rateX812(50));
            }else{
                make.top.equalTo(self.payLineView.mas_bottom).offset(rate750(50));
            }
        }];
        
        _sureLineView = sureLineView;
    }
    return _sureLineView;
}
//label
-(UILabel *)payLabel
{
    if (_payLabel == nil) {
        UILabel *payLabel = [[UILabel alloc] init];
        [self.view addSubview:payLabel];
        //        、、129 128 129
        payLabel.textColor = NumberColor(129, 128, 129);
        payLabel.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        payLabel.textAlignment = NSTextAlignmentLeft;
        payLabel.text = @"支付密码";
        [payLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.payLineView);
            if (isPhoneX) {
                make.bottom.equalTo(self.payLineView.mas_top).offset(-rateX812(15));
            }else{
                make.bottom.equalTo(self.payLineView.mas_top).offset(-rate750(15));
            }
        }];
        _payLabel = payLabel;
    }
    return _payLabel;
}
-(UILabel *)sureLabel
{
    if (_sureLabel == nil) {
        UILabel *sureLabel = [[UILabel alloc] init];
        [self.view addSubview:sureLabel];
        //        、、129 128 129
        sureLabel.textColor = NumberColor(129, 128, 129);
        sureLabel.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        sureLabel.textAlignment = NSTextAlignmentLeft;
        sureLabel.text = @"支付密码";
        [sureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.sureLineView);
            if (isPhoneX) {
                make.bottom.equalTo(self.sureLineView.mas_top).offset(-rateX812(15));
            }else{
                make.bottom.equalTo(self.sureLineView.mas_top).offset(-rate750(15));
            }
        }];
        _sureLabel = sureLabel;
    }
    return _sureLabel;
}
-(OttoTextField *)payPassTextField
{
    if (_payPassTextField == nil) {
        OttoTextField *payPassTextField = [[OttoTextField alloc] init];
        payPassTextField.noPaste = YES;
        [self.view addSubview:payPassTextField];
        payPassTextField.textColor = [UIColor blackColor];
        payPassTextField.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        payPassTextField.placeholder = @"请输入密码";
        payPassTextField.backgroundColor = [UIColor clearColor];
        payPassTextField.borderStyle = UITextBorderStyleNone;
        payPassTextField.textAlignment = NSTextAlignmentLeft;
       
        
        [payPassTextField setKeyboardType:KeyboardTypeNumber];
        [payPassTextField setNumberKeyboardType:NumberKeyboardTypeNumber];
        payPassTextField.textFieldClickReturnDelegate = self;
        
        payPassTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        payPassTextField.keyboardAppearance=UIKeyboardAppearanceDefault;
        payPassTextField.returnKeyType =UIReturnKeyDone;
        [payPassTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        payPassTextField.secureTextEntry = YES;
        [payPassTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.payLabel);
            make.left.equalTo(self.payLabel.mas_right).offset(rate375(20));
            make.right.equalTo(self.payLineView);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(20)));
            }else{
                make.height.equalTo(@(rate750(20)));
            }
        }];
        payPassTextField.tintColor = [UIColor blackColor];
        payPassTextField.delegate = self;
        
        [payPassTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        _payPassTextField = payPassTextField;
    }
    return _payPassTextField;
}

-(OttoTextField *)surePassTextField
{
    if ( _surePassTextField == nil) {
        OttoTextField *surePassTextField = [[OttoTextField alloc] init];
        surePassTextField.noPaste = YES;
        [self.view addSubview:surePassTextField];
        surePassTextField.textColor = [UIColor blackColor];
        surePassTextField.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        surePassTextField.placeholder = @"请确认密码";
        surePassTextField.backgroundColor = [UIColor clearColor];
        surePassTextField.borderStyle = UITextBorderStyleNone;
        surePassTextField.textAlignment = NSTextAlignmentLeft;
    
        surePassTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        surePassTextField.keyboardAppearance=UIKeyboardAppearanceDefault;
        surePassTextField.returnKeyType =UIReturnKeyDone;
        [surePassTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
        surePassTextField.secureTextEntry = YES;
        
        [surePassTextField setKeyboardType:KeyboardTypeNumber];
        [surePassTextField setNumberKeyboardType:NumberKeyboardTypeNumber];
        
        surePassTextField.textFieldClickReturnDelegate = self;
        [surePassTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.sureLabel);
            make.left.equalTo(self.sureLabel.mas_right).offset(rate375(20));
            make.right.equalTo(self.sureLineView);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(20)));
            }else{
                make.height.equalTo(@(rate750(20)));
            }
        }];
        surePassTextField.tintColor = [UIColor blackColor];
        surePassTextField.delegate = self;
        
        [surePassTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        _surePassTextField = surePassTextField;
    }
    return _surePassTextField;
}
-(void)textFieldDidChange:(OttoTextField *)textField
{
    if (textField == _payPassTextField) {
        //获取输入的字段
        NSString *payString = textField.text;
        NSDictionary *attrsDictionary =@{
                                         NSFontAttributeName: _payPassTextField.font,
                                         NSKernAttributeName:[NSNumber numberWithFloat:rate375(6)]//这里修改字符间距
                                         };
        _payPassTextField.attributedText=[[NSAttributedString alloc] initWithString:payString attributes:attrsDictionary];
    }else{
        //获取输入的字段
        NSString *sureString = textField.text;
        NSDictionary *attrsDictionary =@{
                                         NSFontAttributeName: _surePassTextField.font,
                                         NSKernAttributeName:[NSNumber numberWithFloat:rate375(6)]//这里修改字符间距
                                         };
        _surePassTextField.attributedText=[[NSAttributedString alloc] initWithString:sureString attributes:attrsDictionary];
    }
}

#pragma UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    if ([string isEqualToString:@""]) {
        return YES;
    }


    //限制输入的字段长度
    if (textField == _payPassTextField) {
        if (textField.text.length >= 6) {
            [_payPassTextField resignFirstResponder];
            [_surePassTextField becomeFirstResponder];
            return NO;
        }else{
            return YES;
        }
    }else{
        if (textField.text.length >= 6) {
            [self.view endEditing:YES];
            return NO;
        }else{
            return YES;
        }
    }
}

-(UILabel *)postLabel
{
    if (_postLabel == nil) {
        UILabel *postLabel = [[UILabel alloc] init];
        [self.view addSubview:postLabel];
        postLabel.textColor = NumberColor(129, 128, 129);
        postLabel.text = @"注：提款密码由6位数字组成";
        postLabel.font = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
        postLabel.textAlignment = NSTextAlignmentLeft;
        [postLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.sureLineView);
            if (isPhoneX) {
                make.top.equalTo(self.sureLineView.mas_bottom).offset(rateX812(20));
            }else{
                make.top.equalTo(self.sureLineView.mas_bottom).offset(rate750(20));
            }
        }];
        _postLabel = postLabel;
    }
    return _postLabel;
}

-(SYNoHeightedButton *)sureButton
{
    if (_sureButton == nil) {
        
        SYNoHeightedButton *sureButton = [SYNoHeightedButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:sureButton];
        [sureButton setBackgroundImage:[UIImage imageWithColor:zhidianAlprColor(0.3)] forState:UIControlStateDisabled];
        [sureButton setBackgroundImage:[UIImage imageWithColor:zhidainMainColor] forState:UIControlStateNormal];
        [sureButton setTitle:@"确认" forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        sureButton.titleLabel.font = [UIFont systemFontOfSize:font16ScreenWRate * LKScreenW];
        sureButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.width.equalTo(@(rate375(284)));
            make.centerX.equalTo(self.view);
            
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(48)));
                make.top.equalTo(self.postLabel.mas_bottom).offset(rateX812(20));
            }else{
                make.height.equalTo(@(rate750(48)));
                make.top.equalTo(self.postLabel.mas_bottom).offset(rate750(20));
            }
            
        }];
        sureButton.enabled = NO;
        [sureButton addTarget:self action:@selector(sureButtonClick:) forControlEvents:UIControlEventTouchDown];
        sureButton.layer.cornerRadius = 5.0f;
        sureButton.layer.masksToBounds = YES;
        
        _sureButton = sureButton;
    }
    return _sureButton;
}

@end





